package cn.bearspark.common.parse.html;

import cn.bearspark.common.parse.Parser;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * img 标签的解析器
 *
 * @author f
 */
public class TagImgParser extends Parser<HtmlTextParseContext> {
    @Override
    public void parse() {
        HtmlTextParseContext context = pipeline().getContext();
        String src = context.getBody();
        List<String> emojiUrlList = new ArrayList<>();
        int index = 0;
        while (true) {
            int openIndex = src.indexOf("<img src=\"", index);
            if (openIndex == -1) {
                context.setEmojiUrlList(emojiUrlList);
                context.setBody(src);
                return;
            }
            int closeIndex = src.indexOf("\">", openIndex);
            emojiUrlList.add(src.substring(openIndex + "<img src=\"".length(), closeIndex));
            src = src.substring(0, openIndex) +
                  "<i>" +
                  src.substring(closeIndex + "\">".length());
            index = closeIndex + "\">".length();
        }
    }

    @Override
    public void unparse() {
        HtmlTextParseContext context = pipeline().getContext();
        String tar = context.getBody();
        List<String> emojiUrlList = context.getEmojiUrlList();
        if (CollectionUtils.isEmpty(emojiUrlList)) {
            return;
        }
        int index = 0;
        int emojiUrlIndex = 0;
        while (true) {
            int openIndex = tar.indexOf("<i>", index);
            if (openIndex == -1) {
                context.setBody(tar);
                return;
            }
            tar = tar.substring(0, openIndex) +
                  "<img src=\"" +
                  emojiUrlList.get(emojiUrlIndex++) +
                  "\">" +
                  tar.substring(openIndex + "<i>".length());
            index = tar.indexOf("\">", openIndex) + "\">".length();
        }
    }
}
